<template>
  <div class="app-container">
    <h1>自定义表单</h1>
    <el-row :gutter="20">
      <el-col v-for="(template, index) in templates" :key="template.id" :span="6" :index="index">
        <el-card class="card" shadow="hover">
          <h4 class="title">{{ template.name }}</h4>
          <div class="buttom">
            <el-button type="primary" icon="el-icon-edit" circle @click.native="createNew(template.id)" />
            <el-button type="danger" icon="el-icon-delete" circle @click.native="delOne(template.id, index)" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- <el-card
      v-for="template in templates"
      :key="template.id"
      shadow="hover"
      @click.native="createNew(template.id)"
    >{{ template.name }}</el-card>-->
    <el-dialog :title="form_name" :visible.sync="dialogVisible" width="70%" top="5vh">
      <dialogform ref="dialogForm" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="getFormValue">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getAllTemplates, getTemplate, saveOutline, deleteTemplate } from '@/api/customForm'
import { copy as util_Copy } from '@/utils/clone'
import { Message } from 'element-ui'
import dialogform from '../components/dialogForm'
export default {
  components: { dialogform: dialogform },
  data() {
    return {
      templates: [],
      dialogVisible: false,
      dialogTitle: '',
      form_name: '',
      structure: '',
      current_id: 0,
      save_data: ''
    }
  },
  created() {
    getAllTemplates().then(res => {
      this.templates = res.data
    })
  },
  methods: {
    createNew(id) {
      this.current_id = id
      getTemplate(id).then(res => {
        this.structure = res.data.structure
        this.form_name = res.data.name
        this.showDialog()
      })
    },
    showDialog() {
      // console.log(this.structure === '')
      // 弹出预览框
      this.dialogVisible = true
      // 异步调用弹框的方法
      setTimeout(() => {
        // 异步调用弹框中的方法传递表单数据
        this.$refs.dialogForm.setFormVal(util_Copy(JSON.parse(this.structure)))
      })
    },
    getFormValue() {
      this.$refs.dialogForm.getFormVal().then((data) => {
        saveOutline(
          this.current_id,
          { data_list: JSON.stringify(data) }
        ).then(res => {
          Message.success(res.data)
          this.dialogVisible = false
        })
      })
    },
    delOne(id, index) {
      deleteTemplate(id).then(res => {
        this.templates.splice(index, 1)
        this.$notify({
          title: '消息',
          message: res.data,
          type: 'success',
          duration: 2000
        })
      })
    }
  }

}

</script>

<style>
.card{
  /* height: 150px; */
  margin-bottom: 20px;
}
.title{
  text-align: center;
}
.buttom{
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}
</style>
